const MYSQL = require("../../sql/mysql");
const SqlName = "auth_role";
const user_SqlName = "users";
const user_exist = require("../user/module/exist_user");
const MysqlModule = require("../../sql/modules");
const { formatRolesArray } = require("../../utils/format");


// 用户添加角色
async function AddUserRole(params = {}) {
  try {
    let { user, roles,mode } = params;
    if (Array.isArray(roles)) {
      if (!roles.length) {
        throw { code: 500, msg: "添加失败,roles数据为空" };
      }
    } else if (typeof roles == "string" || typeof roles == "number") {
      roles = [roles];
    } else {
      throw { code: 500, msg: "添加失败,roles类型出错" };
    }

    let { userInfo } = await user_exist({ id: user });
      let { new_role } = userInfo;
    let roleListResult = await MysqlModule.List("roles");
    let roleList = roleListResult.data;
    roles = roles.filter((item) => roleList.some((a) => a.id == item));
    new_role = new_role.filter((item) =>
      roleList.some((a) => a.id == item.role_id)
    );
    let rolesArray = [];
    if (new_role) {
      rolesArray = formatRolesArray(roles, new_role);
    } else {
      rolesArray = formatRolesArray(roles);
    }
    return await MysqlModule.Update(user_SqlName, {
      where: `id=${user}`,
      update: {
        new_role: JSON.stringify(rolesArray),
      },
    });
  } catch (error) {
    throw error;
  }
}
// 用户删除角色
async function RemoveUserRole(params = {}) {
  try {
    let { user, roles } = params;
    if (Array.isArray(roles)) {
      if (!roles.length) {
        throw { code: 500, msg: "添加失败,roles数据为空" };
      }
    } else if (typeof roles == "string" || typeof roles == "number") {
      roles = [roles];
    } else {
      throw { code: 500, msg: "添加失败,roles类型出错" };
    }
  } catch (error) {}
}
// 用户设置角色

// 角色列表
async function RoleList(params = {}) {
  return MysqlModule.List(SqlName);
}
// 添加角色
async function addRole(params = {}) {}
// 删除角色
async function removeRole(params = {}) {
  let { id } = params;
  return MysqlModule.Delete(SqlName, { id });
}
// 修改角色
async function updateRole(params = {}) {}
// 添加行为权限
async function addRoleAction(params = {}) {}
// 删除行为权限
async function removeRoleAction(params = {}) {}
// 清空行为权限
async function emptyRoleAction(params = {}) {}
module.exports = {
  AddUserRole,
};
